package com.learn.rabbit.base.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * TODO
 *
 * @author zhousiqi
 * @version 1.0.0
 * @date 2019/2/27 11:59
 */
@Component
@Slf4j
public class JacksonUtil {

    @Resource
    private ObjectMapper objectMapper;

    public String writeValueAsString(Object value) {
        String result;
        try {
            result = objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            result = null;
            log.error("{}解析失败：{}", value, e.getMessage());
        }
        return result;
    }

    public <T> T read(String value, Class<T> tClass){
        try {
            return objectMapper.readValue(value, tClass);
        } catch (IOException e) {
            log.error("{}解析失败：{}", value, e.getMessage());
            return null;
        }
    }

    public <T> T read(String value, TypeReference<T> type){
        try {
            return objectMapper.readValue(value, type);
        } catch (IOException e) {
            log.error("{}解析失败：{}", value, e.getMessage());
            return null;
        }
    }
}
